package com.sunny.blog.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sunny.blog.common.annotation.RequiredLogin;
import com.sunny.blog.common.entity.*;
import com.sunny.blog.pojo.*;
import com.sunny.blog.service.*;
import com.sunny.blog.util.AesUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: BlogController
 * @Description:
 * @Author: sunt
 * @Date: 2020/4/14 14:00
 * @Version 1.0
 **/
@RestController
@RequestMapping("blog")
@Slf4j
public class BlogController {

    @Autowired
    private BlogInfoService blogInfoService;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private ICacheService cacheService;
    @Autowired
    private OpenApiService openApiService;
    /**
     * 新增或更新博客
     * @param blogInfoBean
     * @return
     */
    @PostMapping("addOrUpdateBlog")
    @RequiredLogin(required = true)
    public ResponseResult<String> addOrUpdateBlog(@RequestBody BlogInfoBean blogInfoBean) {
        try {
            if(StrUtil.isNotBlank(blogInfoBean.getId())) {
                blogInfoService.updateBlog(blogInfoBean);
            }else {
                blogInfoService.insertBlog(blogInfoBean);
            }
            return Response.makeOKRsp(MessageConst.OPER_SUCC);
        } catch (Exception e) {
            e.printStackTrace();
            return Response.makeErrRsp();
        }
    }

    /**
     * 查询博客分类
     * @return
     */
    @PostMapping("queryBlogType")
    public ResponseResult<List<BlogTypeBean>> queryBlogTypeList() {
        try {
            List<BlogTypeBean> typeList = blogInfoService.queryBlogTypeList();
            return Response.makeOKRsp(typeList);
        } catch (Exception e) {
            e.printStackTrace();
            return Response.makeErrRsp();
        }
    }

    /**
     * 查询博客标签
     * @return
     */
    @PostMapping("queryBlogTag")
    public ResponseResult<List<BlogTagBean>> queryBlogTagList() {
        try {
            List<BlogTagBean> tagList = blogInfoService.queryBlogTagList();
            return Response.makeOKRsp(tagList);
        } catch (Exception e) {
            e.printStackTrace();
            return Response.makeErrRsp();
        }
    }

    /**
     * 前端博客查询
     * @return
     */
    @PostMapping("queryBlogList")
    public ResponseResult<IPage<BlogInfoBean>> queryBlogList(@RequestBody QueryBlogBean blogBean) {
        try {
            IPage<BlogInfoBean> blogList = blogInfoService.queryBlogPage(blogBean);
            return Response.makeOKRsp(blogList);
        } catch (Exception e) {
            e.printStackTrace();
            return Response.makeErrRsp();
        }
    }

    /**
     * 博客详情查询
     * @param map
     * @return
     */
    @BlogLogInterface(value = SysConstant.QUERY_BLOG_DETAIL)
    @PostMapping("queryBlogDetail")
    public ResponseResult<String> queryBlogDetail(@RequestBody Map map) {
        try {
            String id = map.get("id").toString();
            if(StrUtil.isBlank(id)) {
                return Response.makeErrRsp("非法请求");
            }
            //更新阅读数
            blogInfoService.updateBrowseNum(id);
            List<BlogInfoBean> blogList = blogInfoService.queryBlogDetail(id);
            return Response.makeOKRsp(AesUtil.enCode(JSONUtil.toJsonStr(blogList), MessageConst.PRIVATE_KEY));
        } catch (Exception e) {
            e.printStackTrace();
            return Response.makeErrRsp();
        }
    }

    /**
     * 首页右侧侧边栏信息查询
     * 为符合前端解析要求，此处代码写的巨烂
     * @return
     */
    @PostMapping("queryRightInfo")
    public ResponseResult<RightInfoBean> queryRightInfo() {
        RightInfoBean bean = new RightInfoBean();
        try {
            //查询博主基本信息
            UserInfoBean userInfoBean = userInfoService.queryUserByName("sunny");
            List<BloggerInfoBean> bloggerList = userInfoService.queryBloggerInfo(userInfoBean.getUserId());
            userInfoBean.setBloggerList(bloggerList);
            List<UserInfoBean> userList = new ArrayList<>();
            userList.add(userInfoBean);
            bean.setUserBeanList(userList);
            //热门排行信息
            IPage<BlogInfoBean> ranking = blogInfoService.queryRanking();
            bean.setRankBeanList(ranking.getRecords());
            //标签云信息
            List<TagGroupBean> tagList = blogInfoService.queryTagGroupInfo();
            bean.setTagList(tagList);
            return Response.makeOKRsp(bean);
        } catch (Exception e) {
            e.printStackTrace();
            return Response.makeErrRsp();
        }
    }

    /**
     * 详情页右侧边栏信息
     * @return
     */
    @PostMapping("queryDetailRightInfo")
    public ResponseResult<DetailRightInfoBean> queryDetailRightInfo(@RequestBody Map map) {
        DetailRightInfoBean bean = new DetailRightInfoBean();
        try {
            String blogId = map.get("id").toString();
            //分类信息筛选
            List<BlogTypeBean> typeList = blogInfoService.queryBlogTypeGroupInfo();
            bean.setBlogTypeList(typeList);
            //相似文章
            IPage<BlogInfoBean> similarPage = blogInfoService.querySimilar(blogId);
            bean.setSimilarList(similarPage.getRecords());
            //热门排行信息
            IPage<BlogInfoBean> ranking = blogInfoService.queryRanking();
            bean.setRankBeanList(ranking.getRecords());

            return Response.makeOKRsp(bean);
        } catch (Exception e) {
            e.printStackTrace();
            return Response.makeErrRsp();
        }
    }

    /**
     * 公告信息查询
     * @return
     */
    @PostMapping("queryBlogNotice")
    public ResponseResult<List<BlogNoticeBean>> queryBlogNotice() {
        try {
            List<BlogNoticeBean> noticeList = blogInfoService.queryNoticeList();
            return Response.makeOKRsp(noticeList);
        } catch (Exception e) {
            e.printStackTrace();
            return Response.makeErrRsp();
        }
    }

    /**
     * 最新评论查询
     * @param map
     * @return
     */
    @PostMapping("queryBlogComment")
    public ResponseResult<List<BlogCommentBean>> queryBlogComment(@RequestBody Map map) {
        try {
            String blogId = map.get("id").toString();
            List<BlogCommentBean> commentList = blogInfoService.queryBlogComment(blogId);
            return Response.makeOKRsp(commentList);
        } catch (Exception e) {
            e.printStackTrace();
            return Response.makeErrRsp();
        }
    }

    /**
     * 友链查询
     * @return
     */
    @PostMapping("queryBlogLink")
    @BlogLogInterface(value = SysConstant.QUERY_BLOG_LINK)
    public ResponseResult<List<BlogLinkBean>> queryBlogLink() {
        try {
            List<BlogLinkBean> linkList = blogInfoService.queryBlogLinkList();
            return Response.makeOKRsp(linkList);
        } catch (Exception e) {
            e.printStackTrace();
            return Response.makeErrRsp();
        }
    }

    /**
     * 归档查询
     * @return
     */
    @PostMapping("queryBlogTime")
    public ResponseResult<JSONArray> queryBlogTime() {
        try {
            JSONArray jsonArray = blogInfoService.queryBlogTime();
            return Response.makeOKRsp(jsonArray);
        } catch (Exception e) {
            e.printStackTrace();
            return Response.makeErrRsp();
        }
    }

    /**
     * banner查询
     * @return
     */
    @PostMapping("queryBannerList")
    public ResponseResult<List<BlogBannerBean>> queryBannerList() {
        try {
            List<BlogBannerBean> bannerList = blogInfoService.queryBannerList();
            return Response.makeOKRsp(bannerList);
        } catch (Exception e) {
            e.printStackTrace();
            return Response.makeErrRsp();
        }
    }

    /**
     * 友链申请
     * @param blogLinkBean
     * @return
     */
    @PostMapping("insertBlogLink")
    @Transactional
    public ResponseResult<String> insertBlogLink(@RequestBody BlogLinkBean blogLinkBean) {
        try {
            JSONObject jsonObject = blogInfoService.insertBlogLink(blogLinkBean);
            String errMsg = jsonObject.getStr("errMsg");
            if(StrUtil.isNotBlank(errMsg)) {
                return Response.makeErrRsp(errMsg);
            }
            return Response.makeRsp(ResultCode.SUCCESS.code,"申请成功,待审核中...");
        } catch (Exception e) {
            e.printStackTrace();
            return Response.makeErrRsp();
        }
    }
    /**
     * 后台博客信息查询
     * @return
     */
    @PostMapping("queryBackBlog")
    @RequiredLogin(required = true)
    public String queryBackBlog(HttpServletRequest request) {
        IPage<BlogInfoBean> blogPage = null;
        JSONObject jsonObject = new JSONObject();
        try {
            String page = request.getParameter("page");
            String limit = request.getParameter("limit");
            Page<BlogInfoBean> pageBean = new Page<>();
            QueryBlogBean blogBean = new QueryBlogBean();
            blogBean.setCurrentPage(Long.valueOf(page));
            blogBean.setPageSize(Long.valueOf(limit));
            blogBean.setIsShow("true"); //查询所有
            blogPage = blogInfoService.queryBlogPage(blogBean);
            jsonObject.put("code",0);
            jsonObject.put("msg","查询成功");
            jsonObject.put("count",blogPage.getTotal());
            //数据体组装
            JSONArray dataArray = new JSONArray();
            List<BlogInfoBean> records = blogPage.getRecords();
            for (BlogInfoBean record : records) {
                JSONObject objData = new JSONObject();
                objData.put("id",record.getId());
                objData.put("typeId",record.getTypeId());
                objData.put("title",record.getTitle());
                objData.put("summary", StrUtil.sub(record.getSummary(),0,100));
                objData.put("browseNum",record.getBrowseNum());
                objData.put("commentNum",record.getCommentNum());
                objData.put("releaseDate", DateUtil.formatDateTime(record.getReleaseDate()));
                objData.put("isShow",record.getIsShow() == 0 ? "是":"否");
                dataArray.put(objData);
            }
            jsonObject.put("data",dataArray);

            return JSONUtil.toJsonStr(jsonObject);
        } catch (Exception e) {
            jsonObject.put("code",999);
            jsonObject.put("msg","系统异常");
            jsonObject.put("count",0);
            return JSONUtil.toJsonStr(jsonObject);
        }
    }

    /**
     * 新增博客评论
     * @param commentBean
     * @return
     */
    @PostMapping("insertBlogComment")
    public ResponseResult<String> insertBlogComment(@RequestBody BlogCommentBean commentBean,HttpServletRequest request) {
        try {
            //获取登录信息
            Cookie cookie = ServletUtil.getCookie(request, SysConstant.COMMENT_USER_COOKIE.toLowerCase());
            if(ObjectUtil.isNull(cookie)) {
                return Response.makeErrRsp("登录过期,请刷新页面重新登录");
            }
            String loginToken = cookie.getValue();
            CommentUserBean cacheUser = (CommentUserBean) cacheService.getObjCacheByCode(loginToken);
            //新增评论
            commentBean.setCommentNick(cacheUser.getUserNick());
            commentBean.setCommentEmail(cacheUser.getUserEmail());
            commentBean.setCommentUserId(cacheUser.getUserId());
            IpInfoBean ipInfoBean = openApiService.queryIpInfo(ServletUtil.getClientIP(request));
            commentBean.setCommentIp(ipInfoBean.getIp());
            commentBean.setCommentAddr(ipInfoBean.getAddr());
            String commentId = blogInfoService.insertBlogComment(commentBean);
            //审核评论内容(标题和内容都审核)
            JSONObject jsonObject = blogInfoService.examineComment(commentBean.getCommentNick() + commentBean.getCommentContent());
            int code = jsonObject.getInt("code");
            if(code == ResultCode.FAIL.code) {
                String msg = jsonObject.getStr("msg");
                //记录审核失败原因
                blogInfoService.updateCommentRemark(commentId,msg);
                return Response.makeErrRsp(msg);
            }
            //审核通过 更新状态
            blogInfoService.updateCommentState(commentId);
            //更新博客评论数量
            blogInfoService.updateBlogCommentCnt(commentBean.getBlogId());
            return Response.makeOKRsp(MessageConst.OPER_SUCC);
        } catch (Exception e) {
            e.printStackTrace();
            return Response.makeErrRsp();
        }
    }

    /**
     * 评论回复
     * @param replyBean
     * @return
     */
    @PostMapping("insertBlogReply")
    public ResponseResult<String> insertBlogReply(@RequestBody BlogReplyBean replyBean,HttpServletRequest request) {
        try {
            Cookie cookie = ServletUtil.getCookie(request, SysConstant.COMMENT_USER_COOKIE.toLowerCase());
            if(ObjectUtil.isNull(cookie)) {
                return Response.makeErrRsp("未登录，请刷新页面登录");
            }
            String loginToken = cookie.getValue();
            CommentUserBean cacheUser = (CommentUserBean) cacheService.getObjCacheByCode(loginToken);
            if(ObjectUtil.isNull(cacheUser)) {
                return Response.makeErrRsp("登录失效，请刷新页面登录");
            }
            replyBean.setReplyUserId(cacheUser.getUserId());
            blogInfoService.insertBlogReply(replyBean);
            return Response.makeOKRsp(MessageConst.OPER_SUCC);
        } catch (Exception e) {
            e.printStackTrace();
            return Response.makeErrRsp();
        }
    }

}
